<template>
  <div class="register-container">
    <h1 class="main-title">健康生活助手</h1>
    <el-card class="box-card">
      <h2>开启健康之旅</h2>
      <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-position="left"
          label-width="120px"
          class="register-form"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="uname">
          <el-input v-model="ruleForm.uname"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input
              type="password"
              v-model="ruleForm.pass"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password">
          <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="ruleForm.code">
            <template #append>
              <el-button @click="sendVerificationCode" :disabled="isSendingCode ||!ruleForm.email">
                {{ isSendingCode? `${countdown}s后重试` : '发送验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="agreement" label-width="0" class="agreement-item">
          <el-checkbox v-model="ruleForm.agreement" class="agreement-checkbox">
            我已阅读并同意
            <el-button type="text" @click="showPrivacyPolicy">《用户协议》</el-button>
          </el-checkbox>
        </el-form-item>
      </el-form>
      <div class="btnGroup">
        <el-button type="primary" @click="submitForm('ruleForm')" v-loading="loading" class="register-button">
          注册
        </el-button>
        <div class="extra-links">
          <el-button @click="resetForm('ruleForm')" type="text">重置</el-button>
          <el-button @click="goBack" type="text">返回登录</el-button>
        </div>
      </div>
    </el-card>
    <el-dialog
      title="用户协议"
      :visible.sync="privacyDialogVisible"
      width="50%"
      class="privacy-dialog"
      :close-icon-class="'custom-close-icon'">
      <div class="privacy-content">
        <h3>用户协议</h3>
        <div class="privacy-text">
          <p>欢迎使用健康生活助手！我们非常重视您的个人隐私和数据安全。本协议将帮助您了解我们如何收集、使用和保护您的个人信息。</p>
          
          <h4>1. 信息收集</h4>
          <p>我们收集的信息包括：</p>
          <ul>
            <li>基本信息：用户名、邮箱地址</li>
            <li>健康数据：运动记录、饮食记录、睡眠数据等</li>
            <li>使用数据：使用频率、功能偏好等</li>
          </ul>

          <h4>2. 信息使用</h4>
          <p>我们使用收集的信息用于：</p>
          <ul>
            <li>提供个性化健康建议</li>
            <li>改进我们的服务</li>
            <li>发送重要通知</li>
            <li>防止欺诈和提升安全性</li>
          </ul>

          <h4>3. 信息保护</h4>
          <p>我们采取严格的安全措施保护您的信息：</p>
          <ul>
            <li>数据加密存储</li>
            <li>访问权限控制</li>
            <li>定期安全审计</li>
          </ul>

          <h4>4. 信息共享</h4>
          <p>除非法律要求或获得您的明确同意，我们不会与第三方共享您的个人信息。</p>

          <h4>5. 您的权利</h4>
          <p>您有权：</p>
          <ul>
            <li>访问您的个人信息</li>
            <li>更正不准确的信息</li>
            <li>删除您的账户</li>
            <li>撤回同意</li>
          </ul>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="privacyDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.password!== "") {
          this.$refs.ruleForm.validateField("password");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value!== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (value === "") {
        callback(new Error("请输入邮箱"));
      } else if (!emailRegex.test(value)) {
        callback(new Error("请输入有效的邮箱地址"));
      } else {
        callback();
      }
    };
    var validateAgreement = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请阅读并同意用户协议'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        uname: "",
        pass: "",
        password: "",
        email: "",
        code: "",
        agreement: false
      },
      rules: {
        uname: [
          { required: true, message: "用户名不能为空！", trigger: "blur" }
        ],
        pass: [
          { required: true, validator: validatePass, trigger: "blur" }
        ],
        password: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ],
        email: [
          { required: true, validator: validateEmail, trigger: "blur" }
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" }
        ],
        agreement: [
          { required: true, validator: validateAgreement, trigger: 'change' }
        ]
      },
      loading: false,
      isSendingCode: false,
      countdown: 60,
      timer: null,
      privacyDialogVisible: false
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        this.loading = true;
        if (valid) {
          let _this = this;
          this.axios({
            url: "/api/user/register",
            method: "post",
            headers: {
              "Content-Type": "application/json"
            },
            data: {
              username: _this.ruleForm.uname,
              password: _this.ruleForm.password,
              email: _this.ruleForm.email
            },
            params: {
              inputCode: _this.ruleForm.code
            }
          }).then((res) => {
            this.loading = false;
            if (res.data.success === true) {
              // 注册成功，跳转到登录页面
              this.$router.push('/');
              this.$message({
                message: res.data.message, // 提示注册成功信息
                type: "success"
              });
            } else {
              // 注册失败，显示错误提示
              this.$message({
                message: res.data.message, // 提示失败信息
                type: "warning"
              });
            }
          }).catch((error) => {
            this.loading = false;
            // 请求出错时的提示
            this.$message({
              message: "注册请求失败，请稍后再试",
              type: "error"
            });
            console.error(error);
          });
        } else {
          this.loading = false;
          console.log("error submit!!");
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    goBack() {
      this.$router.go(-1);
    },
    sendVerificationCode() {
      // 检查邮箱格式是否有效
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!emailRegex.test(this.ruleForm.email)) {
        this.$message({
          message: "请输入有效的邮箱地址",
          type: "warning"
        });
        return; // 如果邮箱格式无效，直接返回，避免执行后续代码
      }

      // 邮箱格式正确，开始倒计时
      this.isSendingCode = true;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.timer);
          this.isSendingCode = false;
          this.countdown = 60;
        }
      }, 1000);

      // 发送验证码请求
      this.axios({
        url: "/api/user/sendEmail",
        method: "post",
        params: {
          email: this.ruleForm.email
        }
      }).then((res) => {
        if (res.data.message) {
          this.$message({
            message: res.data.message,
            type: "success"
          });
        } else {
          this.$message({
            message: res.data.error,
            type: "warning"
          });
        }
      }).catch(() => {
        this.$message({
          message: "请求出错，请稍后再试",
          type: "error"
        });
        clearInterval(this.timer);
        this.isSendingCode = false;
        this.countdown = 60;
      });
    },
    showPrivacyPolicy() {
      this.privacyDialogVisible = true;
    }
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(120deg, #e3f2fd, #bbdefb, #fce4ec, #f8bbd0);
  position: relative;
}

.main-title {
  margin: 40px 0;
  font-size: 46px;
  font-weight: bold;
  font-family: "STXingkai", "华文行楷", "Microsoft YaHei", "微软雅黑", sans-serif;
  background: linear-gradient(120deg, #1976d2, #2196f3, #ec407a);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.12);
  letter-spacing: 8px;
  position: relative;
  padding: 10px 20px;
}

.main-title::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(120deg, rgba(33, 150, 243, 0.1), rgba(236, 64, 122, 0.1));
  transform: skew(-15deg);
  z-index: -1;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.main-title::after {
  content: '健康生活助手';
  position: absolute;
  top: 2px;
  left: 2px;
  z-index: -2;
  background: linear-gradient(120deg, #64b5f6, #f48fb1);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  opacity: 0.3;
}

.box-card {
  width: 500px;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(33, 150, 243, 0.1);
  background: linear-gradient(to bottom, #ffffff, #f8f8ff);
  border: 1px solid rgba(33, 150, 243, 0.2);
  margin-bottom: 40px;
  position: relative;
  overflow: hidden;
}

.box-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6px;
  background: linear-gradient(90deg, #2196f3, #ec407a);
}

.box-card h2 {
  background: linear-gradient(120deg, #1976d2, #d81b60);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  text-align: center;
  margin-bottom: 50px;
  font-weight: 600;
  font-size: 36px;
}

.el-form-item {
  margin-bottom: 35px;
}

.register-form >>> .el-form-item__label {
  background: linear-gradient(120deg, #1976d2, #d81b60);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: 500;
  font-size: 18px;
  line-height: 45px;
}

.el-input >>> .el-input__inner {
  height: 45px;
  line-height: 45px;
  font-size: 16px;
  border-radius: 10px 0 0 10px;
  background-color: #fff;
  border: 1px solid rgba(33, 150, 243, 0.3);
  transition: all 0.3s ease;
  padding-left: 15px;
}

.el-input >>> .el-input__inner:focus {
  border-color: #2196f3;
  box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
}

.btnGroup {
  margin-top: 40px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.register-button {
  width: 100%;
  height: 50px;
  font-size: 18px;
  letter-spacing: 2px;
  margin-bottom: 25px;
  background: linear-gradient(90deg, #409EFF, #E040FB) !important;
  border: none !important;
  transition: all 0.3s ease !important;
  border-radius: 25px !important;
  display: flex;
  align-items: center;
  justify-content: center;
}

.register-button:hover {
  opacity: 0.9;
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(33, 150, 243, 0.2);
}

.extra-links {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 0 20px;
}

.extra-links .el-button {
  color: #1976d2 !important;
  transition: all 0.3s ease;
  font-size: 16px;
}

.extra-links .el-button:hover {
  color: #ec407a !important;
  transform: translateY(-1px);
}

/* 验证码按钮样式 */
.el-input >>> .el-input-group__append {
  background: #fff;
  border: 1px solid #dcdfe6;
  border-left: none;
  padding: 0 15px;
  min-width: 95px;
}

.el-input >>> .el-input-group__append .el-button {
  color: #606266;
  font-size: 14px;
  padding: 0;
  width: 100%;
  white-space: nowrap;
}

.el-input >>> .el-input-group__append .el-button:hover {
  color: #409EFF;
}

.el-input >>> .el-input-group__append .el-button[disabled] {
  color: #c0c4cc;
  cursor: not-allowed;
  background: #fff;
}

/* 验证码输入框特殊样式 */
.el-form-item[prop="code"] .el-input {
  width: 100%;
}

.el-form-item[prop="code"] .el-input-group {
  display: flex;
}

.el-form-item[prop="code"] .el-input__inner {
  flex: 1;
}

.el-input >>> .el-input-group__append {
  border-radius: 0 10px 10px 0;
}

.agreement-item {
  text-align: left;
  padding-left: 0;
  margin-left: 0;
}

.agreement-checkbox {
  margin-left: 0;
}

/* 放大复选框的样式 */
.agreement-checkbox :deep(.el-checkbox__input) {
  transform: scale(1.25);
}

/* 增强未选中状态的复选框边框可见性 */
.agreement-checkbox :deep(.el-checkbox__inner) {
  width: 18px;
  height: 18px;
  border: 2px solid #c0c4cc;
}

/* 增强hover状态 */
.agreement-checkbox :deep(.el-checkbox__inner:hover) {
  border-color: #409EFF;
}

/* 选中状态样式增强 */
.agreement-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409EFF;
  border-color: #409EFF;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

/* 调整文字大小 */
.agreement-checkbox :deep(.el-checkbox__label) {
  font-size: 16px;
  padding-left: 10px;
}

/* El-form默认居中对齐的样式覆盖 */
.register-form >>> .el-form-item.agreement-item .el-form-item__content {
  margin-left: 0 !important;
  display: flex;
  justify-content: flex-start;
}

.privacy-dialog :deep(.el-dialog__body) {
  padding: 20px 30px;
}

.privacy-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 20px;
}

.privacy-content h3 {
  text-align: left;
  color: #303133;
  margin-bottom: 30px;
  font-size: 24px;
  background: linear-gradient(120deg, #1976d2, #d81b60);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.privacy-content h4 {
  color: #409EFF;
  margin: 20px 0 10px;
  font-size: 18px;
  text-align: left;
}

.privacy-text {
  color: #606266;
  line-height: 1.8;
  font-size: 16px;
  text-align: left;
}

.privacy-text p {
  margin: 10px 0;
  text-align: left;
}

.privacy-text ul {
  padding-left: 20px;
  margin: 10px 0;
  text-align: left;
}

.privacy-text li {
  margin: 5px 0;
  text-align: left;
}

:deep(.el-checkbox__label) {
  font-size: 16px;
  color: #606266;
}

:deep(.el-checkbox__label .el-button--text) {
  font-size: 16px;
  padding: 0 4px;
  color: #409EFF;
}

:deep(.el-checkbox__label .el-button--text:hover) {
  color: #66b1ff;
}

:deep(.el-dialog) {
  border-radius: 15px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
  padding: 15px 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background: #f8f9fa;
}

:deep(.el-dialog__headerbtn) {
  width: 30px;
  height: 30px;
  font-size: 24px;
  right: 15px;
  top: 15px;
  z-index: 10;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-weight: bold;
  font-size: 20px;
  transform: scale(1.3);
  text-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
  transition: all 0.3s;
}

:deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  color: #f56c6c;
  transform: scale(1.5);
  text-shadow: 0 0 8px rgba(245, 108, 108, 0.5);
}
</style>
